package com.dblog.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dblog.server.servlets.*;
import com.google.apphosting.utils.remoteapi.RemoteApiPb.Request;

@SuppressWarnings("unused")
public class TDispatcher extends HttpServlet {


	private static final Logger log = Logger
			.getLogger(TDispatcher.class.getName());

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse rsp)
			throws ServletException, IOException {
		_handle(req, rsp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse rsp)
			throws IOException {
		_handle(req, rsp);
	}

	private void _handle(HttpServletRequest req, HttpServletResponse rsp)
			throws IOException {

		String controller = "Blog";
		String action = "index";
		
		PrintWriter out = rsp.getWriter();

		String uri = (req.getRequestURI());
		String[] tokens = uri.split("/");
		if (tokens.length > 1) {

			if(tokens[1] != null && tokens[1].length() != 0)
			controller = tokens[1].substring(0, 1).toUpperCase()
					+ tokens[1].substring(1);
		}
		if (tokens.length > 2) {
			if(tokens[2] != null && tokens[2].length() != 0)
			action = tokens[2];
		}

		try {
			String name = "com.dblog.server.servlets." + controller;

			String methodName = action + "Action";

			Class<?> cl = Class.forName(name);

			java.lang.reflect.Constructor<?> constructor = cl
					.getConstructor(new Class[] { HttpServletRequest.class,
							HttpServletResponse.class });

			Object invoker = constructor.newInstance(new Object[] { req, rsp });

			Class<?> arguments[] = new Class[] {};

			java.lang.reflect.Method objMethod = cl.getMethod(methodName,
					arguments);
			
			objMethod.invoke(invoker, (Object[]) arguments);
			req.setAttribute("contentView", "/WEB-INF/Views/"+controller+"/"+action+".jsp");
			getServletContext().getRequestDispatcher("/WEB-INF/layout/Layout.jsp").forward(req, rsp);  
			
		} catch (Exception e) {
			rsp.setHeader("Content-Type", "text/plain");
			log.warning("Error on " + req.getRequestURI() + " not found");
			log.warning(e.getMessage());
			
			e.printStackTrace(out);
			out.println("Rabbit has ran away...");
		}
	}

}
